package com.generic.mybatis.dal.dao.criteria;

import com.generic.mybatis.dal.interceptor.automap.TableMapper;
import com.generic.mybatis.dal.interceptor.automap.TableMapperHolder;

import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * @author wuaj
 */
public class InSubSelect implements Criteria {
    private Logger logger = LoggerFactory.getLogger(InSubSelect.class);

    private final String field;

    private final Class subClazz;

    private final String targetField;

    private final Criteria[] criterias;

    public InSubSelect(String field, Class subClazz, String targetField, Criteria[] criterias) {
        this.field = field;
        this.subClazz = subClazz;
        this.targetField = targetField;
        this.criterias = criterias;
    }

    @Override
    public void toSql(TableMapper mapper, SQL sql, Map paramMap) {
        TableMapper newMapper = TableMapperHolder.getTableMapper(subClazz);
//        FieldMapper newFiledMapper = newMapper.getFieldMapperCache().get(targetField);
//        FieldMapper fieldMapper = mapper.getFieldMapperCache().get(field);
        Assert.notNull(newMapper);
//        Assert.assertNotNull(newFiledMapper);
        SQL newSql = new SQL();
        newSql.SELECT(newMapper.getPropertyAlias(targetField));
//        newSql.FROM(String.format("%s %s", newMapper.getTableName(), newMapper.getAlias()));
        newMapper.buildFromStatement(newSql);
        for (Criteria criteria : criterias) {
            criteria.toSql(newMapper, newSql, paramMap);
        }
        sql.WHERE(String.format("%s in (%s)", mapper.getPropertyAlias(field), newSql.toString()));
    }
}
